<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="180" sortable>
			</el-table-column>
			<el-table-column prop="name" label="名称" width="220" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 0" style="color: green">正常</span>
          <span v-else-if="scope.row.state == -1"style="color: red">禁用</span>
          <span v-else style="color: red">未知</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     :current-page="currentPage"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="editForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="editForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="0">正常</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="editForm.manager" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="editForm.parent"
                       :options="deptTree"
                       :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
			  title:"",
				filters: {
          keyword: ''
				},
				departments: [],
        employees:[],
        deptTree:[],
				total: 0,
				currentPage: 1,
        pageSize:8,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {//表单校验规则
					name: [//校验name属性
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
          sn: [//sn
            { required: true, message: '请输入编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				editForm: {
          id: null,
          name: '',
          sn: '',
          dirPath:'',
          state: 0,
          manager: null,
          parent: null
				},
			}
		},
		methods: {
      search(){//高级查询按钮
        // 定位到第一页
        this.currentPage = 1;
        //调用查询刷新页面
        this.getDepartments();
      },
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
			  //请求参数
				let para = {
					currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.filters.keyword//关键字查询
				};
				this.listLoading = true;//开启忙等
        this.$http.post("/dept",para)
            .then(result=>{
              this.listLoading = false;//关闭忙等框
              result = result.data;//PageList
              this.departments = result.rows;
              this.total = result.total;
            })
            .catch(result=>{
              console.log(result);
            })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {// 确定按钮
					this.listLoading = true;//开启忙等框
					this.$http.delete("/dept/"+row.id)//http://localhost:8080/dept/1
              .then(result=>{
                this.listLoading = false;//关闭忙等框
                result = result.data;
                if(result.success){//后端删除成功
                  this.$message({
                    message: result.message,
                    type: 'success'
                  });
                }else{//后端删除失败
                  this.$message({
                    message: result.message,
                    type: 'error'
                  });
                }
                this.currentPage = 1;
                this.getDepartments();//重新刷新页面
              })
              .catch(result=>{//调用后端调用不同
                this.$message({
                  message: '系统繁忙，稍后重试',
                  type: 'error'
                });
              })

				}).catch(() => {//取消按钮
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getDeptTree();
				this.editFormVisible = true;//控制显示弹出框
        this.title = "编辑";
				this.editForm = Object.assign({}, row);
        if(this.editForm.dirPath){//如果不为空
          let arry = this.editForm.dirPath.split("/");//将dirPath整成数组
          let dirPath = [];
          for(let i=1;i<=arry.length-2;i++){
            dirPath.push(parseInt(arry[i]));
          }
          this.editForm.parent = dirPath;
        }
			},
			//显示新增界面
			handleAdd: function () {
        this.getDeptTree();
        this.editFormVisible = true;//控制显示弹出框
        this.title = "新增";
        this.editForm = {// 表单重置
          id: null,
          name: '',
          sn: '',
          dirPath:'',
          state: 0,
          manager: null,
          parent: null
        };

        this.$refs.editForm.resetFields();//重置表单校验
      },
			//新增和编辑提交按钮
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {//校验通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;//提交按钮忙等 防止重复点击
							let para = Object.assign({}, this.editForm);
              if(para.parent){//有值  [2,7]-->{id:7}
                //将数组格式转换成对象
                para.parent = {"id":para.parent[para.parent.length-1]}
              }
              this.$http.put("/dept",para)
                  .then(result=>{
                    this.$refs['editForm'].resetFields();//重置表单校验
                    this.editLoading = false;//关闭按钮忙等
                    this.editFormVisible = false;//关闭弹出框
                    result = result.data;
                    if(result.success){//后端删除成功
                      this.$message({
                        message: result.message,
                        type: 'success'
                      });
                    }else{//后端删除失败
                      this.$message({
                        message: result.message,
                        type: 'error'
                      });
                    }
                    this.currentPage = 1;
                    this.getDepartments();//重新刷新页面
                  })
                  .catch(result=>{//调用后端调用不同
                    this.editLoading = false;//关闭按钮忙等
                    this.$message({
                      message: '系统繁忙，稍后重试',
                      type: 'error'
                    });
                    this.$refs['editForm'].resetFields();//重置表单校验
                  })
            });
          }
        });
			},
			selsChange: function (sels) {//每次点击复选框的时候触发函数
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        //this.sels 当前选中的所有行的数据
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {//确定删除
					this.listLoading = true;
          this.$http.patch("/dept",ids)
              .then(result=>{
                this.listLoading = false;//关闭忙等框
                result = result.data;
                if(result.success){//后端删除成功
                  this.$message({
                    message: result.message,
                    type: 'success'
                  });
                }else{//后端删除失败
                  this.$message({
                    message: result.message,
                    type: 'error'
                  });
                }
                this.currentPage = 1;
                this.getDepartments();//重新刷新页面
              })
              .catch(result=>{//调用后端调用不同
                this.$message({
                  message: '系统繁忙，稍后重试',
                  type: 'error'
                });
              })
				}).catch(() => {//取消

				});
			},
      getEmployees(){
        this.$http.get("/employee")
            .then(result=>{
              this.employees = result.data;//List<Employee>
            })
      },
      getDeptTree(){
        this.$http.get("/dept/tree").then(result=>{
          this.deptTree = result.data;
        })
      }
		},
		mounted() {
			this.getDepartments();
      this.getEmployees();
		}
	}

</script>

<style scoped>

</style>